package com.weblog.user.service;

import com.weblog.model.user.Permission;
import com.weblog.model.user.Role;
import com.weblog.user.dao.PermissionDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;

/**
 * @author MaoLin Wang
 * @date 2019/9/1817:58
 */
@Service
public class PermissionService {

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private IdWorker idWorker;


    /**
     * 权限列表
     * @return
     */
    public List<Permission> permissionList() {
        return permissionDao.findAll();
    }


    /**
     * 新添加权限
     * @param permission
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean addPermission(Permission permission) {
       String token= (String) request.getAttribute("claims_superAadmin");
       if(token ==null || "".equals(token)){
           //非超级管理员
           return false;//权限不足
       }
       //是超级管理员
        permission.setPid(idWorker.nextId()+"");
       permissionDao.save(permission);
       return true;
    }

    /**
     * 根据id查询权限信息
     * @param pid
     * @return
     */
    public Permission getById(String pid) {
        return permissionDao.findById(pid).get();
    }

    /**
     * 修改权限
     * @param permission
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(Permission permission) {
        permissionDao.save(permission);
    }


    /**
     * 删除权限
     * @param pid
     */
    @Transactional(rollbackFor = Exception.class)
    public int delete(String pid) {
        Permission permission = permissionDao.findById(pid).get();
        if(permission!=null){
            Set<Role> roles = permission.getRoles();
            for(Role r : roles){
                r.getPermissions().remove(permission);
            }
            permissionDao.deleteById(pid);
            return 1;
        }
        //权限不存在
        return 0;
    }
}
